'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import ThemeSelector from '@/components/ui/theme-selector';
import { useTheme, ThemeColor } from '@/hooks/use-theme';

export default function SettingsPage() {
  const { data: session, status, update: updateSession } = useSession();
  const router = useRouter();
  const { theme, themeColor, setTheme, setThemeColor } = useTheme();
  const [language, setLanguage] = useState('zh_CN');
  const [emailNotifications, setEmailNotifications] = useState(true);
  const [pushNotifications, setPushNotifications] = useState(true);
  const [loading, setLoading] = useState(true);
  
  // 添加保存操作的状态管理
  const [themeSubmitting, setThemeSubmitting] = useState(false);
  const [notifSubmitting, setNotifSubmitting] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });
  
  // 头像上传相关状态
  const [avatarUploading, setAvatarUploading] = useState(false);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 如果未登录，重定向到登录页
  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/login');
    } else if (status === 'authenticated') {
      // 加载用户现有设置
      fetchUserSettings();
      // 设置头像预览
      if (session?.user?.image) {
        setPreviewImage(session.user.image);
      }
    }
  }, [status, router, session]);

  // 获取用户设置
  const fetchUserSettings = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/user/settings', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
      });
      
      if (!response.ok) {
        throw new Error('获取设置失败');
      }
      
      const data = await response.json();
      console.log('获取的用户设置:', data);
      
      // 设置表单状态
      setTheme(data.theme || 'system');
      setLanguage(data.language || 'zh_CN');
      setEmailNotifications(data.emailNotifications !== undefined ? data.emailNotifications : true);
      setPushNotifications(data.pushNotifications !== undefined ? data.pushNotifications : true);
      
      setMessage({ type: '', text: '' });
    } catch (error) {
      console.error('加载用户设置失败:', error);
      setMessage({ type: 'error', text: '加载设置失败，使用默认值' });
    } finally {
      setLoading(false);
    }
  };

  // 处理头像文件选择
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      setMessage({ type: 'error', text: '请选择图片文件' });
      return;
    }
    
    // 验证文件大小（最大5MB）
    if (file.size > 5 * 1024 * 1024) {
      setMessage({ type: 'error', text: '图片大小不能超过5MB' });
      return;
    }
    
    // 创建预览URL
    const previewUrl = URL.createObjectURL(file);
    setPreviewImage(previewUrl);
  };
  
  // 上传头像
  const uploadAvatar = async () => {
    if (!fileInputRef.current?.files?.[0]) {
      setMessage({ type: 'error', text: '请先选择图片' });
      return;
    }
    
    try {
      setAvatarUploading(true);
      setMessage({ type: '', text: '' });
      
      const formData = new FormData();
      formData.append('avatar', fileInputRef.current.files[0]);
      
      const response = await fetch('/api/user/avatar', {
        method: 'POST',
        body: formData,
        credentials: 'include',
      });
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: '上传失败' }));
        throw new Error(errorData.error || '头像上传失败');
      }
      
      const result = await response.json();
      
      // 更新会话中的用户头像
      if (result.success && result.imageUrl) {
        await updateSession({ user: { image: result.imageUrl } });
      }
      
      setMessage({ type: 'success', text: '头像上传成功' });
    } catch (error) {
      console.error('头像上传失败:', error);
      setMessage({ 
        type: 'error', 
        text: error instanceof Error ? error.message : '头像上传失败'
      });
    } finally {
      setAvatarUploading(false);
    }
  };

  const saveThemeSettings = async () => {
    try {
      setThemeSubmitting(true);
      setMessage({ type: '', text: '' });
      
      const response = await fetch('/api/user/settings/theme', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ theme, themeColor: 'blue' })
      });
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: '保存失败' }));
        throw new Error(errorData.error || '保存主题设置失败');
      }
      
      setMessage({ type: 'success', text: '主题设置已保存' });
    } catch (error) {
      console.error('保存主题设置失败:', error);
      setMessage({ 
        type: 'error', 
        text: error instanceof Error ? error.message : '保存主题设置失败'
      });
    } finally {
      setThemeSubmitting(false);
    }
  };

  const saveNotificationSettings = async () => {
    try {
      setNotifSubmitting(true);
      setMessage({ type: '', text: '' });
      
      const response = await fetch('/api/user/settings/notifications', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ 
          emailNotifications, 
          pushNotifications,
          weeklyDigest: true
        })
      });
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: '保存失败' }));
        throw new Error(errorData.error || '保存通知设置失败');
      }
      
      setMessage({ type: 'success', text: '通知设置已保存' });
    } catch (error) {
      console.error('保存通知设置失败:', error);
      setMessage({ 
        type: 'error', 
        text: error instanceof Error ? error.message : '保存通知设置失败' 
      });
    } finally {
      setNotifSubmitting(false);
    }
  };

  if (loading) {
    return <div className="container mx-auto py-8 px-4">加载中...</div>;
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <h1 className="text-2xl font-bold mb-4">设置</h1>
      
      {/* 状态消息显示 */}
      {message.text && (
        <div className={`mb-4 p-3 rounded ${
          message.type === 'success' ? 'bg-green-100 text-green-800' : 
          message.type === 'error' ? 'bg-red-100 text-red-800' : ''
        }`}>
          {message.text}
        </div>
      )}
      
      {/* 头像设置部分 */}
      <div className="mb-8">
        <h2 className="text-xl font-semibold mb-4">头像设置</h2>
        <div className="flex flex-col sm:flex-row items-center gap-6">
          {/* 头像预览 */}
          <div className="w-32 h-32 relative">
            {previewImage ? (
              <div className="w-full h-full rounded-full overflow-hidden">
                <Image 
                  src={previewImage} 
                  alt="头像预览" 
                  width={128} 
                  height={128} 
                  className="object-cover w-full h-full" 
                />
              </div>
            ) : (
              <Avatar className="w-32 h-32">
                <AvatarFallback className="text-4xl">
                  {session?.user?.name ? session.user.name.charAt(0).toUpperCase() : '?'}
                </AvatarFallback>
              </Avatar>
            )}
          </div>
          
          {/* 上传控件 */}
          <div className="flex flex-col gap-3">
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              accept="image/*"
              className="hidden"
              id="avatar-upload"
            />
            <label 
              htmlFor="avatar-upload" 
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 cursor-pointer text-center"
            >
              选择图片
            </label>
            <button 
              onClick={uploadAvatar}
              disabled={avatarUploading || !previewImage}
              className={`px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 disabled:bg-gray-400`}
            >
              {avatarUploading ? '上传中...' : '上传头像'}
            </button>
            <p className="text-xs text-gray-500 mt-1">
              支持 JPG、PNG 格式，最大 5MB
            </p>
          </div>
        </div>
      </div>
      
      {/* 主题设置部分 */}
      <div className="mb-8">
        <Card highlight themeBg className="rounded-lg overflow-hidden">
          <CardHeader>
            <CardTitle>主题设置</CardTitle>
            <CardDescription>自定义应用的外观</CardDescription>
          </CardHeader>
          <CardContent>
        <div className="mb-4">
              <label className="text-sm font-medium mb-2 block">主题模式</label>
              <div className="grid grid-cols-3 gap-3">
                <Button
                  type="button"
                  variant={theme === 'light' ? 'primary' : 'outline'}
                  className="flex items-center justify-center"
              onClick={() => setTheme('light')}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
                  </svg>
              浅色
                </Button>
                <Button
                  type="button"
                  variant={theme === 'dark' ? 'primary' : 'outline'}
                  className="flex items-center justify-center"
              onClick={() => setTheme('dark')}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                  </svg>
              深色
                </Button>
                <Button
                  type="button"
                  variant={theme === 'system' ? 'primary' : 'outline'}
                  className="flex items-center justify-center"
              onClick={() => setTheme('system')}
            >
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                  </svg>
              系统
                </Button>
          </div>
        </div>
            
            <div className="mb-4">
              <label className="text-sm font-medium mb-2 block">主题颜色</label>
              <ThemeSelector 
                selectedColor={themeColor} 
                onChange={(color) => setThemeColor(color)}
                className="max-w-md"
                showLabels
                size="md"
              />
            </div>
          </CardContent>
          <CardFooter>
            <Button 
              type="button" 
              variant="primary"
          onClick={saveThemeSettings}
              isLoading={themeSubmitting}
        >
              保存主题设置
            </Button>
          </CardFooter>
        </Card>
      </div>
      
      <div className="mb-8">
        <h2 className="text-xl font-semibold mb-4">通知设置</h2>
        <div className="mb-4">
          <label className="flex items-center mb-2">
            <input 
              type="checkbox" 
              className="mr-2" 
              checked={emailNotifications}
              onChange={(e) => setEmailNotifications(e.target.checked)}
              disabled={notifSubmitting}
            /> 
            接收邮件通知
          </label>
          <label className="flex items-center">
            <input 
              type="checkbox" 
              className="mr-2" 
              checked={pushNotifications}
              onChange={(e) => setPushNotifications(e.target.checked)}
              disabled={notifSubmitting}
            /> 
            接收推送通知
          </label>
        </div>
        <button 
          className={`px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 disabled:bg-gray-400`}
          onClick={saveNotificationSettings}
          disabled={notifSubmitting}
        >
          {notifSubmitting ? '保存中...' : '保存通知设置'}
        </button>
      </div>
      
      <div>
        <button 
          className="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600"
          onClick={() => router.push('/dashboard')}
        >
          返回仪表板
        </button>
      </div>
    </div>
  );
} 